package algorithm.tree;

import algorithm.tree.bst.BST;
import algorithm.tree.bst.Entity;
import algorithm.tree.bst.TreeNode;

import java.util.*;

public class PrintTree {
  public static void main(String[] args) {
    //测试插入
    BST bst = new BST();
    //声明
    Random random = new Random();
    for (int i = 0; i < 10; i++) {
      int i1 = random.nextInt(100);
      Entity entity = new Entity(i1, "2");
      bst.put(entity);
    }
    System.out.println("节点数: " + bst.count);
    displayTree(bst.root);
  }

  /**
   * 使用树形结构显示
   */
  public static void displayTree(TreeNode root) {
    Stack globalStack = new Stack();
    globalStack.push(root);
    // int nBlank=32;
    int nBlank = 32;
    boolean isRowEmpty = false;
    String dot = "............................";
    System.out.println(dot + dot + dot);
    while (isRowEmpty == false) {
      Stack localStack = new Stack();
      isRowEmpty = true;
      for (int j = 0; j < nBlank; j++)//{
      {

        System.out.print("-");
      }
      while (globalStack.isEmpty() == false) {
        //里面的while循环用于查看全局的栈是否为空
        TreeNode temp = (TreeNode) globalStack.pop();
        if (temp != null) {
          System.out.print(temp.value.key + " ");

          localStack.push(temp.left);
          localStack.push(temp.right);
          //如果当前的节点下面还有子节点，则必须要进行下一层的循环
          if (temp.left != null || temp.right != null) {
            isRowEmpty = false;

          }
        } else {
          //如果全局的栈则不为空
          System.out.print("* ");
          localStack.push(null);
          localStack.push(null);

        }


        //打印一些空格
        for (int j = 0; j < nBlank * 2 - 2; j++) {
          //System.out.print("&");
          System.out.print(" ");
        }


      }//while end


      System.out.println();
      nBlank /= 2;
      //这个while循环用来判断，local栈是否为空,不为空的话，则取出来放入全局栈中
      while (localStack.isEmpty() == false) {
        globalStack.push(localStack.pop());
      }

      // }
    }//大while循环结束之后，输出换行
    System.out.println(dot + dot + dot);

  }


}



